<?php

namespace app\controller;

use app\model\Headlines;
use think\facade\View;
use think\facade\Request;

class Index
{

    public function index()
    {
        $logined = isset($_COOKIE['login']);
        $count = Headlines::count();
        $limit = 5;
        $keyword = Request::param('keyword');
        $selectArr = Request::param('selectArr');
        $page = Request::param('page', 1);

        $maxPage = $count / $limit + 1;
        if ($page < 1 or $page > $maxPage)
        {
            $page = 1;
        }
        $skip = ($page - 1) * $limit;

        if ($keyword)
        {
            if (strpos($selectArr, 'content'))
            {
                $query = Headlines::where('title', 'like', "%{$keyword}%")->whereOr('content', 'like', "%{$keyword}%", 'or');
            }
            else
            {
                $query = Headlines::where('title', 'like', "%{$keyword}%");
            }
            $count = $query->count();
            $rows = $query->order('id', 'desc')->limit($skip, $limit)->select();
        }
        else
        {
            $rows = Headlines::order('id', 'desc')->limit($skip, $limit)->select();
        }
        View::assign([
            'rows'  => $rows,
            'count' => $count,
            'logined' => $logined,
            'limit' => $limit,
            'page' => $page

        ]);
        return View::fetch();
    }

    public function article()
    {
        $id = Request::param('id');
        $obj = Headlines::find($id);
        View::assign('obj', $obj);
        return View::fetch();
    }

    public function login()
    {
        if ($_POST["username"] == 'admin' && $_POST["password"] == 'admin')
        {
            setcookie("login", "true", time() + 3600, '/');
            header("location: /headlines2/public/index.php");
        }
    }

    public function logout()
    {
        setcookie('login', '', time() - 1, '/');
        header("location: /headlines2/public/index.php");
    }
}
